//
//  PlayScreen.m
//  TestFistGame
//
//  Created by  on 5/17/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "PlayScreen.h"
#import "iCoreGUIController.h"

#define LIGHT_SKILL_COUNT_DOWN  10
#define FIRE_SKILL_COUNT_DOWN   10

@implementation PlayScreen

@synthesize gameMapData, mapBackgroundSprite,temp,setRallyPointMode;
// initialize when a play screen is created

-(id)initPlayScreenWith:(iCoreGUIController *)_mainGUIController withMapDataXmlFile:(NSString *)_mapXmlFile {
    self = [super initGameLayerWith:_mainGUIController];   
    
    windowsSize = [mainGUIController.mainDirector winSize];
    
    //define value for variables of constructin tower, select tower, upgrade tower
    groundIsSelected = nil;
    towerIsSelected = nil;
    
    mainGUIController = _mainGUIController;
    gameMapData = [[MapData alloc]initMapData];
    //mapBackgroundSprite = [[CCSprite alloc]init];
    zoomIn=NO;
    scaleRate=1;
    setRallyPointMode=NO;
    gestureAdded=NO;
    fireSkillCountDown = FIRE_SKILL_COUNT_DOWN;
    lightkillCountDown = LIGHT_SKILL_COUNT_DOWN;
    victoryCondition = NO;
    
    self.isTouchEnabled = TRUE;
    recognizerTap = [[[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanFrom:)] autorelease];
    [[mainGUIController.mainDirector openGLView] addGestureRecognizer:recognizerTap];
    
    doubleTap=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleTapEvent:)];
    doubleTap.numberOfTapsRequired=2;
    [[mainGUIController.mainDirector openGLView] addGestureRecognizer:doubleTap];
    singleTap=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapEvent:)];
    singleTap.numberOfTapsRequired=1;
    //[[mainGUIController.mainDirector openGLView] addGestureRecognizer:singleTap];
    
    [self loadResources:_mapXmlFile];
    
    return self;
}

-(void)update:(ccTime)timeUpdate {  
    [super update:timeUpdate];
    if (setRallyPointMode && !gestureAdded){
        gestureAdded=YES;
        [mainGUIController.mainDirector.openGLView addGestureRecognizer:singleTap];
        NSLog(@"Gesture Added");
    }
    if (!setRallyPointMode && gestureAdded){
        gestureAdded=NO;
        [mainGUIController.mainDirector.openGLView removeGestureRecognizer:singleTap];
        NSLog(@"Gesture Removed");
    }
    //NSLog(@"Wave index: %d",waveIndex);
    //NSLog(@"Enemy Index: %d", enemyIndex);
    if(waveIndex==gameMapData.waves.count && !victoryCondition){
        victoryCondition = YES;
        for (int i=0;i<listGameObject.count;i++){
            if ([[listGameObject objectAtIndex:i]isKindOfClass:[Enemy class]]){
                victoryCondition=NO;
                break;
            }
        }
        if (victoryCondition){
            //[mainGUIController cleanupFrameCacheSprite];
            //[self schedule:@selector(showVictoryScreen:) interval:5.0];
            [self performSelector:@selector(showVictoryScreen) withObject:nil afterDelay:5.0f];
            //[self showVictoryScreen];
        }
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// CODE FOR GROUP BACKGROUND FUNCTIONS
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

-(void)loadMapData:(NSString *)_mapDataXmlFileName {
    gameMapData = [mainGUIController.dataAccess getMapDataWith:_mapDataXmlFileName];
    
    [self loadGameComponents];
    
    //[self schedule:@selector(startWave:)];    
    
    //Play background sound
    //[mainGUIController playBackgroundSound:AUDIO_PLAY_SCREEN_BACKGROUND_1 withLoop:YES];
    //[mainGUIController setBackgroundSoundVolume:0.5];
}

-(void)loadResources:(NSString *)_mapXmlFile {
    //load goblin plist resource file
    [mainGUIController loadGraphicFromPlistFileToFrameCache:PLIST_RESOURCE_GOBLIN];
    [mainGUIController loadGraphicFromPlistFileToFrameCache:PLIST_RESOURCE_GARGOYGLE];
    [mainGUIController loadGraphicFromPlistFileToFrameCache:PLIST_RESOURCE_HERO];
    [mainGUIController loadGraphicFromPlistFileToFrameCache:PLIST_RESOURCE_HERO02];
    [mainGUIController loadGraphicFromPlistFileToFrameCache:PLIST_RESOURCE_MAGIC_CIRCLE];
    [mainGUIController loadGraphicFromPlistFileToFrameCache:PLIST_RESOURCE_BOOM_TOWER];
    [mainGUIController loadGraphicFromPlistFileToFrameCache:PLIST_RESOURCE_MAGIC_TOWER];
    [mainGUIController loadGraphicFromPlistFileToFrameCache:PLIST_RESOURCE_FAST_TOWER];
    [mainGUIController loadGraphicFromPlistFileToFrameCache:PLIST_RESOURCE_STONE_BULLET];
    //[mainGUIController loadGraphicFromPlistFileToFrameCache:PLIST_RESOURCE_DEMON_LORD];
    [mainGUIController loadGraphicFromPlistFileToFrameCache:PLIST_RESOURCE_SUMMONER];
    [mainGUIController loadGraphicFromPlistFileToFrameCache:PLIST_RESOURCE_HOUND];
    [mainGUIController loadGraphicFromPlistFileToFrameCache:PLIST_RESOURCE_BARRACK_TOWER];
    [mainGUIController loadGraphicFromPlistFileToFrameCache:PLIST_RESOURCE_FIRE_DROP];
    [mainGUIController loadGraphicFromPlistFileToFrameCache:PLIST_RESOURCE_FIRE_DROP_EFFECT];
    [mainGUIController loadGraphicFromPlistFileToFrameCache:PLIST_RESOURCE_SILVER_LIGHT_EFFECT];
    [mainGUIController loadGraphicFromPlistFileToFrameCache:PLIST_RESOURCE_STAR_EFFECT];
    [mainGUIController loadGraphicFromPlistFileToFrameCache:PLIST_RESOURCE_MAGIC_RAY];
    [mainGUIController loadGraphicFromPlistFileToFrameCache:PLIST_RESOURCE_THUNDER_LIGHT_EFFECT];
    [mainGUIController loadGraphicFromPlistFileToFrameCache:PLIST_RESOURCE_BLOOD_C];
    [mainGUIController loadGraphicFromPNGToFrameCache:@"Images/PlayScreen/castle1.png" withRowCount:1 withColumnCount:4];
    //[mainGUIController loadGraphicFromPNGToFrameCache:IMAGE_NAME_MAGIC_TOWER withRowCount:6 withColumnCount:6];
    [mainGUIController loadGraphicFromPNGToFrameCache:IMAGE_NAME_BOOM_TOWER withRowCount:3 withColumnCount:5];
    
    [self loadMapData:_mapXmlFile];
}

-(void)loadGameComponents { 
    //draw map
    [self drawMap];
    //Draw player information on top-right screen
    [self drawPlayerInfo];
    
    [self drawRightTableContainTowerIcon];
    
    [self drawSpecialAttack];
    [self drawStartWaveCircle];
    [self drawCallHeroButton];
    
    //add mute speaker menu icon
    //create 2 menu item image, this show speaker normal image fist
    CCMenuItemImage *speakerControl = [CCMenuItemImage itemFromNormalImage:IMAGE_OTHER_SPEAKER_NORMAL selectedImage:IMAGE_OTHER_SPEAKER_MUTE target:nil selector:nil];
    
    //this menuItemImage show speaker mute image fist
    CCMenuItemImage *speakerControlReverse = [CCMenuItemImage itemFromNormalImage:IMAGE_OTHER_SPEAKER_MUTE selectedImage:IMAGE_OTHER_SPEAKER_NORMAL target:nil selector:nil];
    
    //Create toogle to switch between speakerControl and speakerControlReverse
    CCMenuItemToggle *speakerMenuItem = nil;
    if(mainGUIController.isMuteSound)
        speakerMenuItem = [CCMenuItemToggle itemWithTarget:self selector:@selector(muteAllSound:) items:speakerControlReverse, speakerControl, nil];
    else
        speakerMenuItem = [CCMenuItemToggle itemWithTarget:self selector:@selector(muteAllSound:) items:speakerControl, speakerControlReverse, nil];
    speakerMenuItem.scale = 1.25f;
    
    CCMenu *speakerMenu = [CCMenu menuWithItems:speakerMenuItem, nil];
    speakerMenu.position = ccp(25, 300);
    [self addChild:speakerMenu z:10];
    
    //Draw pause game button
    CCMenuItemImage *pauseGameButton = [CCMenuItemImage itemFromNormalImage:IMAGE_PAUSE_GAME_BUTTON_NORMAL selectedImage:IMAGE_PAUSE_GAME_BUTTON_SELECTED target:self selector:@selector(pauseGame)];
    pauseGameButton.scale = 0.9f;
    CCMenu *pauseGameMenu = [CCMenu menuWithItems:pauseGameButton, nil];
    pauseGameMenu.position = ccp(65, 298);
    [self addChild:pauseGameMenu z:10];
}

-(void)drawMap {
    //load map imageBackground
    //mapBackgroundSprite = gameMapData.mapSprite;
    //mapBackgroundSprite = [[CCSprite alloc]initWithFile:gameMapData.mapBackground];
    //mapBackgroundSprite=[[CCTMXTiledMap alloc]initWithTMXFile:@"MapData/temp.tmx"];
    mapBackgroundSprite=[[CCTMXTiledMap alloc]initWithTMXFile:gameMapData.mapBackground];;
    [gameMapData getTowersPositionsFromTileMap];
    [gameMapData getWaypointsFromTileMap];
    mapBackgroundSprite.position = ccp(-mapBackgroundSprite.contentSize.width + 480, -mapBackgroundSprite.contentSize.height +320);
    mapBackgroundSprite.anchorPoint = ccp(0, 0);
    [self addChild:mapBackgroundSprite z:0];
    
    //draw constructionGround and add it into listGameObject of gameLayer
    for(int i = 0; i < gameMapData.towersPos.count; i++) {
        ConstructionGround *ground = [[ConstructionGround alloc]initConstructionGroundWith:self];
        ground.spriteBody.position = [[gameMapData.towersPos objectAtIndex:i] CGPointValue];
        [mapBackgroundSprite addChild:ground.spriteBody];
        
        //add ground object on listGameObject of GameLayer
        [self addGameObject:ground];
    }
    
    Summoner *summoner=[[Summoner alloc]initSummmonerWith:self];
    [mapBackgroundSprite addChild:summoner.spriteBody];
    [self addGameObject:summoner];
    CGPoint lastPoint=[[[gameMapData.ways objectAtIndex:0]objectAtIndex:[[gameMapData.ways objectAtIndex:0]count]-1] CGPointValue];
    CGPoint secondLastPoint=[[[gameMapData.ways objectAtIndex:0]objectAtIndex:[[gameMapData.ways objectAtIndex:0]count]-2] CGPointValue];
    int direction=[self directionFromPoint:lastPoint toDestinationPoint:secondLastPoint];
    if(direction==DIRECTION_UP){
        summoner.spriteBody.position=ccpAdd(lastPoint, ccp(0,30));
    }
    else if(direction==DIRECTION_LEFT){
        summoner.spriteBody.position=ccpAdd(lastPoint, ccp(30,0));
    }
    else if(direction==DIRECTION_DOWN){
        summoner.spriteBody.position=ccpAdd(lastPoint, ccp(0,-30));
    }
    else if(direction==DIRECTION_RIGHT){
        summoner.spriteBody.position=ccpAdd(lastPoint, ccp(-30,0));
    }
    if (direction==DIRECTION_RIGHT)
        summoner.spriteBody.flipX=YES;
    //end fixed
    
    //fixed
    mainGUIController.playerData.life=10;
    mainGUIController.playerData.money=gameMapData.startingMoney;
}

-(void)drawPlayerInfo {    
    //remove all old  values
    [moneyCountText removeFromParentAndCleanup:YES];
    [lifeCountText removeFromParentAndCleanup:YES];
    [starCountText removeFromParentAndCleanup:YES];
    
    [self removeChildByTag:TAG_PLAYER_MONEY_ICON cleanup:YES];
    [self removeChildByTag:TAG_PLAYER_STAR_ICON cleanup:YES];
    [self removeChildByTag:TAG_PLAYER_LIFE_ICON cleanup:YES];
    
    moneyCountText = [CCLabelTTF labelWithString:[NSString stringWithFormat:@"%d", mainGUIController.playerData.money] fontName:FONT_COMIC_BOOK fontSize:16];
    moneyCountText.anchorPoint = ccp(1, 1);
    moneyCountText.position = ccp(windowsSize.width - 5, windowsSize.height - 15);
    moneyCountText.color = ccc3(255, 255, 64);
    [self addChild:moneyCountText z:10];
    
    CCSprite *moneyIcon = [CCSprite spriteWithFile:IMAGE_PLAYER_INFO_MONEY];
    moneyIcon.anchorPoint = ccp(1, 1);
    moneyIcon.position = ccp(windowsSize.width - 5 - moneyCountText.contentSize.width, windowsSize.height);
    [self addChild:moneyIcon z:10 tag:TAG_PLAYER_MONEY_ICON];
    
    starCountText = [CCLabelTTF labelWithString:[NSString stringWithFormat:@"%d", mainGUIController.playerData.star] fontName:FONT_COMIC_BOOK fontSize:16];
    starCountText.anchorPoint = ccp(1, 1);
    starCountText.position = ccp(windowsSize.width - 25 - moneyCountText.contentSize.width - moneyIcon.contentSize.width, windowsSize.height - 15);
    starCountText.color = ccc3(255, 255, 64);
    [self addChild:starCountText z:10];
    
    CCSprite *starIcon = [CCSprite spriteWithFile:IMAGE_PLAYER_INFO_STAR];
    starIcon.anchorPoint = ccp(1, 1);
    starIcon.position = ccp(windowsSize.width - 25 - starCountText.contentSize.width - moneyCountText.contentSize.width - moneyIcon.contentSize.width, windowsSize.height);
    [self addChild:starIcon z:10 tag:TAG_PLAYER_STAR_ICON];
    
    lifeCountText = [CCLabelTTF labelWithString:[NSString stringWithFormat:@"%d", mainGUIController.playerData.life] fontName:FONT_COMIC_BOOK fontSize:16];
    lifeCountText.anchorPoint = ccp(1, 1);
    lifeCountText.position = ccp(windowsSize.width - 45 - starIcon.contentSize.width - starCountText.contentSize.width - moneyCountText.contentSize.width - moneyIcon.contentSize.width, windowsSize.height - 15);
    lifeCountText.color = ccc3(255, 255, 64);
    [self addChild:lifeCountText z:10];
    
    CCSprite *lifeIcon = [CCSprite spriteWithFile:IMAGE_PLAYER_INFO_LIFE];
    lifeIcon.anchorPoint = ccp(1, 1);
    lifeIcon.position = ccp(windowsSize.width - 45 - lifeCountText.contentSize.width - starIcon.contentSize.width - starCountText.contentSize.width - moneyCountText.contentSize.width - moneyIcon.contentSize.width, windowsSize.height);
    [self addChild:lifeIcon z:10 tag:TAG_PLAYER_LIFE_ICON];
    
    playerNameText = [CCLabelTTF labelWithString:mainGUIController.playerData.playerName fontName:FONT_COMIC_BOOK fontSize:16];
    playerNameText.anchorPoint = ccp(1, 1);
    playerNameText.position = ccp(windowsSize.width, windowsSize.height);
    playerNameText.color = ccc3(255, 255, 64);
    //[self addChild:playerNameText];
    //fixed
    if(mainGUIController.playerData.life <= 0) {
        [self unscheduleUpdate];
        //[listGameObject removeAllObjects];
        [self stopAllActions];
        mainGUIController.playerData.life=10;
        [mainGUIController PlayGameOverScreenWithCurrentScreen:self];
    }
}

-(void)drawSpecialAttack {
    //draw table background
    
    CCSprite *fireSkillNormalState = [CCSprite spriteWithFile:IMAGE_SPECIAL_ATTACH_FIRE];
    CCSprite *fireSkillActiveState = [CCSprite spriteWithFile:IMAGE_SPECIAL_ATTACH_FIRE];
    CCSprite *fireMask = [[CCSprite alloc]initWithFile:IMAGE_FIRE_ICON];
    fireMask.color = ccc3(255,200,2);
    fireMask.scale = 2.0f;
    fireMask.opacity = 75;
    fireMask.position = ccp(fireSkillActiveState.contentSize.width/2, fireSkillActiveState.contentSize.height/2);
    [fireSkillActiveState addChild:fireMask];

    CCMenuItemSprite *fireSkillMenuItem = [CCMenuItemSprite itemFromNormalSprite:fireSkillNormalState selectedSprite:fireSkillActiveState target:self selector:@selector(callFireDropAttack:)];
    fireSkillMenuItem.scale = 0.75f;
    fireSkillButton = [CCMenu menuWithItems:fireSkillMenuItem, nil];
    fireSkillButton.position = ccp(fireSkillMenuItem.contentSize.width/2 + 5, fireSkillMenuItem.contentSize.height/2 + 5);
    [self addChild:fireSkillButton z:10];
    
    blackSpriteOfFireSkill = [[CCSprite alloc]initWithFile:@"Images/blank.png"];
    blackSpriteOfFireSkill.color = ccc3(0, 0, 0);
    blackSpriteOfFireSkill.textureRect = CGRectMake(0, 0, fireSkillNormalState.contentSize.width - 5, fireSkillNormalState.contentSize.height - 5);
    blackSpriteOfFireSkill.opacity = 95;
    blackSpriteOfFireSkill.anchorPoint = ccp(0.5, 0);
    blackSpriteOfFireSkill.position = ccp(fireSkillNormalState.contentSize.width/2, 5);
    [fireSkillNormalState addChild:blackSpriteOfFireSkill];
    
    fireEffect = [[CCSprite alloc]init];
    fireEffect.position = ccp(fireSkillNormalState.contentSize.width/2, 10);
    [fireSkillNormalState addChild:fireEffect];
    
    NSMutableArray *fireEffectFrames = [mainGUIController loadAnimationWithNumberOfFrames:24 withFrameName:@"star_effect"];
    CCAnimation *fireEffectAnimation = [CCAnimation animationWithFrames:fireEffectFrames delay:0.05f];
    [fireEffect runAction:[CCRepeatForever actionWithAction:[CCAnimate actionWithAnimation:fireEffectAnimation restoreOriginalFrame:YES]]];
    
    fireEffect.visible = NO;
    
    CCSprite *lightSkillNormalState = [CCSprite spriteWithFile:IMAGE_SPECIAL_ATTACH_SILVER_LIGHT];
    CCSprite *lightSkillActiveState = [CCSprite spriteWithFile:IMAGE_SPECIAL_ATTACH_SILVER_LIGHT];
    CCSprite *lightMask = [CCSprite spriteWithFile:IMAGE_FIRE_ICON];
    lightMask.color = ccc3(0,230,255);
    lightMask.scale = 2.0f;
    lightMask.opacity = 75;
    lightMask.position = ccp(lightSkillActiveState.contentSize.width/2, lightSkillActiveState.contentSize.height/2);
    [lightSkillActiveState addChild:lightMask];
    
    CCMenuItemSprite *lightSkillMenuItem = [CCMenuItemSprite itemFromNormalSprite:lightSkillNormalState selectedSprite:lightSkillActiveState target:self selector:@selector(callSilverLightAttack:)];
    lightSkillMenuItem.scale = 0.75f;
    silverLightSkillButton = [CCMenu menuWithItems:lightSkillMenuItem, nil];
    silverLightSkillButton.position = ccp(lightSkillMenuItem.contentSize.width/2*3, lightSkillMenuItem.contentSize.height/2 + 5);
    [self addChild:silverLightSkillButton z:10]; 
    
    blackSpriteOfLightSkill = [[CCSprite alloc]initWithFile:@"Images/blank.png"];
    blackSpriteOfLightSkill.color = ccc3(0, 0, 0);
    blackSpriteOfLightSkill.textureRect = CGRectMake(0, 0, lightSkillNormalState.contentSize.width - 5, lightSkillNormalState.contentSize.height - 5);
    blackSpriteOfLightSkill.opacity = 95;
    blackSpriteOfLightSkill.anchorPoint = ccp(0.5, 0);
    blackSpriteOfLightSkill.position = ccp(lightSkillNormalState.contentSize.width/2, 5);
    [lightSkillNormalState addChild:blackSpriteOfLightSkill];
    
    //draw linghtning on des
    lightningEffect = [[CCSprite alloc]init];
    lightningEffect.position = ccp(lightSkillNormalState.contentSize.width/2, 5);
    lightningEffect.scaleX = 0.8f;
    [lightSkillNormalState addChild:lightningEffect];
    
    NSMutableArray *lightningFrames = [mainGUIController loadAnimationWithNumberOfFrames:12 withFrameName:@"thunder_light_effect"];
    CCAnimation *lightningAnimation = [CCAnimation animationWithFrames:lightningFrames delay:0.05];
    [lightningEffect runAction:[CCRepeatForever actionWithAction:[CCSequence actions:[CCAnimate actionWithAnimation:lightningAnimation restoreOriginalFrame:YES], [CCDelayTime actionWithDuration:0.5f], nil]]];
    
    lightningEffect.visible = NO;
    
    fireSkillButton.isTouchEnabled = NO;
    silverLightSkillButton.isTouchEnabled = NO;
    
    [self schedule:@selector(fullSkillCountDown) interval:0.5f];
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// END CODE FOR GROUP BACKGROUND FUNCTIONS
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// CODE FOR CONSTRUCT TOWER
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

-(void)drawRightTableContainTowerIcon {
    rightTableContain = [[CCSprite alloc]initWithFile:IMAGE_RIGHT_TABLE_CONSTAIN_ICON];
    rightTableContain.anchorPoint =ccp(0, 0.5f);
    rightTableContain.position = ccp(windowsSize.width, windowsSize.height /2);
    rightTableContain.visible = NO;
    rightTableContain.opacity = 220;
    [self addChild:rightTableContain z:1000];
    
    CCMenuItemImage *boomTowerButton = [CCMenuItemImage itemFromNormalImage:IMAGE_BOOM_TOWER_ITEM selectedImage:nil disabledImage:nil target:self selector:@selector(createBoomTowerOnConstructionGround)];
    boomTowerButton.position = ccp(0, 0);
    
    CCLabelTTF *boomTowerPriceLabel = [CCLabelTTF labelWithString:[NSString stringWithFormat:@"$%d", BOOM_TOWER_CONSTRUCTION_PRICE] fontName:FONT_COMIC_BOOK fontSize:11];
    boomTowerPriceLabel.position = ccp(boomTowerButton.contentSize.width/2, -5);
    boomTowerPriceLabel.color = ccc3(255, 254, 64);
    [boomTowerButton addChild:boomTowerPriceLabel];
    
    CCMenuItemImage *magicTowerButton = [CCMenuItemImage itemFromNormalImage:IMAGE_MAGIC_TOWER_ITEM selectedImage:nil disabledImage:nil target:self selector:@selector(createMagicTowerOnConstructionGround)];
    magicTowerButton.position = ccp(0, 0);
    
    CCLabelTTF *magicTowerPriceLabel = [CCLabelTTF labelWithString:[NSString stringWithFormat:@"$%d", MAGIC_TOWER_CONSTRUCTION_PRICE] fontName:FONT_COMIC_BOOK fontSize:11];
    magicTowerPriceLabel.position = ccp(magicTowerButton.contentSize.width/2, -5);
    magicTowerPriceLabel.color = ccc3(255, 254, 64);
    [magicTowerButton addChild:magicTowerPriceLabel];
    
    CCMenuItemImage *fastTowerButton = [CCMenuItemImage itemFromNormalImage:IMAGE_FAST_TOWER_ITEM selectedImage:nil disabledImage:nil target:self selector:@selector(createFastTowerOnConstructionGround)];
    fastTowerButton.position = ccp(0, 0);
    
    CCLabelTTF *fastTowerPriceLabel = [CCLabelTTF labelWithString:[NSString stringWithFormat:@"$%d", FAST_TOWER_CONSTRUCTION_PRICE] fontName:FONT_COMIC_BOOK fontSize:11];
    fastTowerPriceLabel.position = ccp(fastTowerButton.contentSize.width/2, -5);
    fastTowerPriceLabel.color = ccc3(255, 254, 64);
    [fastTowerButton addChild:fastTowerPriceLabel];
    
    CCMenuItemImage *barrackTowerButton = [CCMenuItemImage itemFromNormalImage:IMAGE_BARRACK_TOWER_ITEM selectedImage:nil disabledImage:nil target:self selector:@selector(createBarrackTowerOnConstructionGround)];
    barrackTowerButton.position = ccp(0, 0);
    
    CCLabelTTF *barrackTowerPriceLabel = [CCLabelTTF labelWithString:[NSString stringWithFormat:@"$%d", BARRACK_TOWER_CONSTRUCTION_PRICE] fontName:FONT_COMIC_BOOK fontSize:11];
    barrackTowerPriceLabel.position = ccp(barrackTowerButton.contentSize.width/2, -5);
    barrackTowerPriceLabel.color = ccc3(255, 254, 64);
    [barrackTowerButton addChild:barrackTowerPriceLabel];
    
    CCMenu *listTowerIconMenu = [CCMenu menuWithItems:boomTowerButton, magicTowerButton, fastTowerButton, barrackTowerButton, nil];
    [listTowerIconMenu alignItemsVerticallyWithPadding:20.0f];
    listTowerIconMenu.position = ccp(60/2, rightTableContain.contentSize.height/2);
    
    [rightTableContain addChild:listTowerIconMenu z:1000];
    
    CCMenuItemImage *hideIcon = [CCMenuItemImage itemFromNormalImage:IMAGE_HIDE_RIGHT_TABLE_ICON selectedImage:IMAGE_HIDE_RIGHT_TABLE_ICON_SELECTED target:self selector:@selector(hideRightTableContainTowerIconButtonPress)];
    hideIcon.position = ccp(0, 0);
    CCMenu *hideIconMenu = [CCMenu menuWithItems:hideIcon, nil];
    hideIconMenu.anchorPoint = ccp(0.5, 0.5);
    hideIconMenu.position = ccp(- hideIcon.contentSize.width/2 + 2, rightTableContain.contentSize.height/2);
    [rightTableContain addChild:hideIconMenu];
}

-(void)hideRightTableContainTowerIconButtonPress {
    [self toggleVisibleStateRightTableContainTowerIcon];
    groundIsSelected = nil;
}

-(void)toggleVisibleStateRightTableContainTowerIcon {
    if(rightTableContain.visible == NO) {
        rightTableContain.visible = YES;
        [rightTableContain runAction:[CCSequence actions:[CCMoveTo actionWithDuration:0.25f position:ccp(windowsSize.width - 65, rightTableContain.position.y)],[CCMoveBy actionWithDuration:0.15f position:ccp(10, 0)],[CCMoveBy actionWithDuration:0.15f position:ccp(-5, 0)], nil]];
    } else {
        //close right table
        [rightTableContain runAction:[CCSequence actions:[CCMoveTo actionWithDuration:0.25f position:ccp(windowsSize.width, rightTableContain.position.y)],[CCHide action], nil]];
    }
}

-(void)sharkRightTableContainTowerIcon {
    if(rightTableContain.visible == YES) {
        [rightTableContain runAction:[CCSequence actions:[CCMoveBy actionWithDuration:0.15f position:ccp(5, 0)],[CCMoveBy actionWithDuration:0.15f position:ccp(-10, 0)],[CCMoveBy actionWithDuration:0.15f position:ccp(5, 0)], nil]];
    }
}

-(void)constructionGroundPress:(id)sender {    
    BOOL isCancelSelectGround = NO;
    
    if(groundIsSelected == nil) {
        [self toggleVisibleStateRightTableContainTowerIcon];
    }
    else {
        if(groundIsSelected == sender) {
            //cancel select ground if touch second
            groundIsSelected = nil;
            
            isCancelSelectGround = YES;
            
            //hide right table icon
            [self toggleVisibleStateRightTableContainTowerIcon];
        } else {
            [self sharkRightTableContainTowerIcon];
        }
    }
    
    if(!isCancelSelectGround) {
        groundIsSelected = sender;
    }
}

-(void)createBoomTowerOnConstructionGround {
    NSLog(@"remove ground and create tower");      
    //create boom tower on that position
    //buy if enough money
    if(BOOM_TOWER_CONSTRUCTION_PRICE <= mainGUIController.playerData.money) {
        BoomTower *boomTower = [[BoomTower alloc]initBoomTowerWith:self];
        boomTower.spriteBody.position = groundIsSelected.spriteBody.position;
        [boomTower findAndFireTarget];
        
        //add boom tower object on array listTowerConstructed to control it
        //[listTowerConstructed addObject:boomTower];
        [self addGameObject:boomTower];
        
        //add boom tower sprite on mapBackgroundSprite to show
        [mapBackgroundSprite addChild:boomTower.spriteBody];
        
        //remove ground object
        //[listConstructionGround removeObject:_constructionGround];
        //[self removeGameObject:_constructionGround];
        
        //and remove ground spriteBody on mapbackgroundSprite
        [groundIsSelected.spriteBody removeFromParentAndCleanup:YES];
        
        //remove construct tower stick note
        //[mapBackgroundSprite removeChildByTag:TAG_CONSTRUCT_TOWER_STICK_NOTE_SPRITE cleanup:YES];
        
        //degree player money
        mainGUIController.playerData.money -= BOOM_TOWER_CONSTRUCTION_PRICE;
        [self drawPlayerInfo];
    } else {
        //not enough money
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"STOP" message:[NSString stringWithFormat:@"You don't have enough money to construct it\nYour money: %d$", mainGUIController.playerData.money] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
    }
    
    groundIsSelected = nil;
    [self toggleVisibleStateRightTableContainTowerIcon];
}

-(void)createMagicTowerOnConstructionGround {
    NSLog(@"remove ground and create tower");    
    
    //create boom tower on that position
    //buy if enough money
    if(BOOM_TOWER_CONSTRUCTION_PRICE <= mainGUIController.playerData.money) {
        MagicTower *nagicTower = [[MagicTower alloc]initMagicTowerWith:self];
        nagicTower.spriteBody.position = groundIsSelected.spriteBody.position;
        
        //add boom tower object on array listTowerConstructed to control it
        //[listTowerConstructed addObject:boomTower];
        [self addGameObject:nagicTower];
        
        //add boom tower sprite on mapBackgroundSprite to show
        [mapBackgroundSprite addChild:nagicTower.spriteBody];
        
        //remove ground object
        //[listConstructionGround removeObject:_constructionGround];
        //[self removeGameObject:_constructionGround];
        
        //and remove ground spriteBody on mapbackgroundSprite
        [groundIsSelected.spriteBody removeFromParentAndCleanup:YES];
        
        //remove construct tower stick note
//        [mapBackgroundSprite removeChildByTag:TAG_CONSTRUCT_TOWER_STICK_NOTE_SPRITE cleanup:YES];
        
        //degree player money
        mainGUIController.playerData.money -= BOOM_TOWER_CONSTRUCTION_PRICE;
        [self drawPlayerInfo];
    } else {
        //not enough money
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"STOP" message:[NSString stringWithFormat:@"You don't have enough money to construct it\nYour money: %d$", mainGUIController.playerData.money] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
    }
    
    groundIsSelected = nil;
    [self toggleVisibleStateRightTableContainTowerIcon];
}

-(void)createBarrackTowerOnConstructionGround {
    NSLog(@"remove ground and create tower");   
    
    //create boom tower on that position
    //buy if enough money
    if(BOOM_TOWER_CONSTRUCTION_PRICE <= mainGUIController.playerData.money) {
        BarrackTower *barrackTower = [[BarrackTower alloc]initBarrackTowerWith:self];
        barrackTower.spriteBody.position = groundIsSelected.spriteBody.position;
        [barrackTower createStartRallyPoint];
        [barrackTower newRallyPoint:barrackTower.rallyPoint.position];
        [barrackTower create3SoldierAtStart];
        //add boom tower object on array listTowerConstructed to control it
        //[listTowerConstructed addObject:boomTower];
        [self addGameObject:barrackTower];
        
        //add boom tower sprite on mapBackgroundSprite to show
        [mapBackgroundSprite addChild:barrackTower.spriteBody];
        
        //remove ground object
        //[listConstructionGround removeObject:_constructionGround];
        //[self removeGameObject:_constructionGround];
        
        //and remove ground spriteBody on mapbackgroundSprite
        [groundIsSelected.spriteBody removeFromParentAndCleanup:YES];
        
        //remove construct tower stick note
//        [mapBackgroundSprite removeChildByTag:TAG_CONSTRUCT_TOWER_STICK_NOTE_SPRITE cleanup:YES];
        
        //degree player money
        mainGUIController.playerData.money -= BOOM_TOWER_CONSTRUCTION_PRICE;
        [self drawPlayerInfo];
    } else {
        //not enough money
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"STOP" message:[NSString stringWithFormat:@"You don't have enough money to construct it\nYour money: %d$", mainGUIController.playerData.money] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
    }
    
    groundIsSelected = nil;
    [self toggleVisibleStateRightTableContainTowerIcon];
}

-(void)createFastTowerOnConstructionGround {
    NSLog(@"remove ground and create fast tower");  
    
    //create boom tower on that position
    //buy if enough money
    if(FAST_TOWER_CONSTRUCTION_PRICE <= mainGUIController.playerData.money) {
        FastTower *fastTower = [[FastTower alloc]initFastTowerWith:self];
        fastTower.spriteBody.position = groundIsSelected.spriteBody.position;
        
        //add boom tower object on array listTowerConstructed to control it
        //[listTowerConstructed addObject:boomTower];
        [self addGameObject:fastTower];
        
        //add boom tower sprite on mapBackgroundSprite to show
        [mapBackgroundSprite addChild:fastTower.spriteBody];
        
        //remove ground object
        //[listConstructionGround removeObject:_constructionGround];
        //[self removeGameObject:_constructionGround];
        
        //and remove ground spriteBody on mapbackgroundSprite
        [groundIsSelected.spriteBody removeFromParentAndCleanup:YES];
        
        //remove construct tower stick note
//        [mapBackgroundSprite removeChildByTag:TAG_CONSTRUCT_TOWER_STICK_NOTE_SPRITE cleanup:YES];
        
        //degree player money
        mainGUIController.playerData.money -= FAST_TOWER_CONSTRUCTION_PRICE;
        [self drawPlayerInfo];
    } else {
        //not enough money
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"STOP" message:[NSString stringWithFormat:@"You don't have enough money to construct it\nYour money: %d$", mainGUIController.playerData.money] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
    }
    
    groundIsSelected = nil;
    [self toggleVisibleStateRightTableContainTowerIcon];
}

-(void)sellTower:(GameObject *)_towerObject {
    //sub money
    mainGUIController.playerData.money += ((TowerObject *)_towerObject).buyPrice * 0.4;
    [self drawPlayerInfo];
    
    //create construction ground on tower position
    ConstructionGround *ground = [[ConstructionGround alloc]initConstructionGroundWith:self];
    ground.spriteBody.position = _towerObject.spriteBody.position;
    //add ground object on listGameObject of GameLayer
    [self addGameObject:ground];
    [mapBackgroundSprite addChild:ground.spriteBody];
    
    //remove tower
    //[listTowerConstructed removeObject:_towerObject];
    [self removeGameObject:_towerObject];
    [_towerObject.spriteBody removeFromParentAndCleanup:YES];
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// END CODE FOR CONSTRUCT TOWER
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

-(void)fullSkillCountDown {
    if(fireSkillCountDown > 0) {
        fireSkillCountDown--;
        blackSpriteOfFireSkill.scaleY = 1.0f/FIRE_SKILL_COUNT_DOWN * fireSkillCountDown;
        
        if(fireSkillCountDown == 0) { 
            fireEffect.visible = YES;
            fireSkillButton.isTouchEnabled = YES;
        }
    }
    
    if(lightkillCountDown > 0) {
        lightkillCountDown--;
        blackSpriteOfLightSkill.scaleY = 1.0f/LIGHT_SKILL_COUNT_DOWN * lightkillCountDown;
        
        if(lightkillCountDown == 0) {
            silverLightSkillButton.isTouchEnabled = YES;
            lightningEffect.visible = YES;
        }
    }
}

-(void)drawStartWaveCircle {
    CCSprite *startWaveCircle = [CCSprite spriteWithFile:IMAGE_START_WAVE_CIRCLE];
    [startWaveCircle runAction:[CCRepeatForever actionWithAction:[CCSequence actions:[CCScaleTo actionWithDuration:2 scale:0.5],[CCScaleTo actionWithDuration:2 scale:1.2], nil]]];
    CCMenuItemSprite *startWaveItem = [CCMenuItemSprite itemFromNormalSprite:startWaveCircle selectedSprite:nil target:self selector:@selector(pressStartWave:)];
    startWaveMenu = [CCMenu menuWithItems:startWaveItem, nil];
    
    //fixed
    CGPoint beginPoint=[[[gameMapData.ways objectAtIndex:0] objectAtIndex:0] CGPointValue];
    CGPoint nextPoint=[[[gameMapData.ways objectAtIndex:0] objectAtIndex:1] CGPointValue];
    int direction=[self directionFromPoint:beginPoint toDestinationPoint:nextPoint];
    [mapBackgroundSprite addChild:startWaveMenu z:0];
    if (direction==DIRECTION_UP){
        startWaveMenu.position = ccp(beginPoint.x,beginPoint.y+30);
    }
    else if (direction==DIRECTION_RIGHT){
        startWaveMenu.position = ccp(beginPoint.x-30,beginPoint.y);
    }
    else if (direction==DIRECTION_DOWN){
        startWaveMenu.position = ccp(beginPoint.x,beginPoint.y-30);
    }
    else if (direction==DIRECTION_LEFT){
        startWaveMenu.position = ccp(beginPoint.x+30,beginPoint.y);
    }
    //end fixed
    
    startWaveCircle.anchorPoint=ccp(0.5,0.5);
    startWaveCircle.position=ccp(40,25);
    
    CCLabelTTF *callWaveNote = [CCLabelTTF labelWithString:@"Tap to start Enemy wave!" fontName:FONT_COMIC_BOOK fontSize:12];
    callWaveNote.color = ccc3(255, 255, 64);
    callWaveNote.position = ccp(startWaveCircle.contentSize.width/2, 0);
    [startWaveCircle addChild:callWaveNote];
}

-(void)drawCallHeroButton {
    CCSprite *callHero = [CCSprite spriteWithFile:IMAGE_CALL_HERO];
    [callHero runAction:[CCRepeatForever actionWithAction:[CCSequence actions:[CCScaleTo actionWithDuration:2 scale:0.5],[CCScaleTo actionWithDuration:2 scale:1.2], nil]]];
    CCMenuItemSprite *callHeroItem = [CCMenuItemSprite itemFromNormalSprite:callHero selectedSprite:nil target:self selector:@selector(callHero:)];
    callHeroMenu = [CCMenu menuWithItems:callHeroItem, nil];
    
    //fixed
    CGPoint lastPoint=[[[gameMapData.ways objectAtIndex:0] objectAtIndex:    [[gameMapData.ways objectAtIndex:0] count]-1] CGPointValue];
    CGPoint secondLastPoint=[[[gameMapData.ways objectAtIndex:0] objectAtIndex:    [[gameMapData.ways objectAtIndex:0] count]-2] CGPointValue];
    [mapBackgroundSprite addChild:callHeroMenu z:10];
    
    int direction=[self directionFromPoint:lastPoint toDestinationPoint:secondLastPoint];
    if (direction==DIRECTION_UP){
        callHeroMenu.position = ccp(lastPoint.x,lastPoint.y+50);
    }
    else if (direction==DIRECTION_RIGHT){
        callHeroMenu.position = ccp(lastPoint.x-50,lastPoint.y);
    }
    else if (direction==DIRECTION_DOWN){
        callHeroMenu.position = ccp(lastPoint.x,lastPoint.y-50);
    }
    else if (direction==DIRECTION_LEFT){
        callHeroMenu.position = ccp(lastPoint.x+50,lastPoint.y);
    }
    //end fixed
    
    callHero.anchorPoint=ccp(0.5,0.5);
    callHero.position=ccp(25,25);
}

//calling when clicked mute icon
-(void)muteAllSound:(id)sender {
    [mainGUIController setMuteSoundPlayer:!mainGUIController.isMuteSound]; 
}

//start a new wave
-(void)startWave:(ccTime)delta{
    if(waveIndex<gameMapData.waves.count){
        [self schedule:@selector(createEnemy:) interval:2];
        [self unschedule:@selector(startWave:)];
        
        //Play sound
        //[mainGUIController playEffect:AUDIO_START_WAVE];
    }
}

//create enemy in a wave
-(void)createEnemy:(ccTime)delta{
    if (enemyIndex<[[gameMapData.waves objectAtIndex:waveIndex]count]){
        EnemyInfo *enemyInfo=[[gameMapData.waves objectAtIndex:waveIndex] objectAtIndex:enemyIndex];
        enemyIndex++;
        [self createEnemyWithEnemyInfo:enemyInfo];
    }
    if(enemyIndex==[[gameMapData.waves objectAtIndex:waveIndex]count]){
        waveIndex++;
        enemyIndex=0;
        [self unschedule:@selector(createEnemy:)];
        [self schedule:@selector(startWave:) interval:10];
    }
    if (waveIndex==gameMapData.waves.count){
        [self unschedule:@selector(createEnemy:)];
    }
}

-(void)showVictoryScreen {
    //save player data on NSUserDefault
    int bonus=0;
    if (mainGUIController.playerData.life>=8)
        bonus+=3;
    else if (mainGUIController.playerData.life>=5&&mainGUIController.playerData.life<8)
        bonus+=2;
    else
        bonus+=1;
    mainGUIController.playerData.star += bonus;
    NSMutableDictionary *playerData = [mainGUIController.playerData convertDataToDictionary];
    NSUserDefaults *dataStored = [NSUserDefaults standardUserDefaults];
    [dataStored setObject:playerData forKey:@"playerData"];
    
    [self stopAllActions];
    //[self unschedule:@selector(showVictoryScreen:)];
    [mainGUIController PlayVictoryScreenWithCurrentScreen:self withBonus:bonus];
}

//create enemy from map data
-(void)createEnemyWithEnemyInfo:(EnemyInfo*)_enemyInfo{
    Enemy *unknownEnemy;
    if([_enemyInfo.enemyType isEqualToString:@"Goblin"]){
        unknownEnemy=[[Goblin alloc]initGoblinWith:self withRoad:[gameMapData.ways objectAtIndex:_enemyInfo.waypointID]];
    }
    else if ([_enemyInfo.enemyType isEqualToString:@"Hound"]){
        unknownEnemy=[[Hound alloc]initHoundWith:self withRoad:[gameMapData.ways objectAtIndex:_enemyInfo.waypointID]];
    }
    else if ([_enemyInfo.enemyType isEqualToString:@"Gargoygle"]){
        unknownEnemy=[[Gargoygle alloc]initGargoygleWith:self withRoad:[gameMapData.ways objectAtIndex:_enemyInfo.waypointID]];
    }
    else if ([_enemyInfo.enemyType isEqualToString:@"Demon Lord"]){
        unknownEnemy=[[DemonLord alloc]initDemonLordWith:self withRoad:[gameMapData.ways objectAtIndex:_enemyInfo.waypointID]];
    }
    CGPoint startPosition=[[[gameMapData.ways objectAtIndex:_enemyInfo.waypointID]objectAtIndex:0]CGPointValue];
    unknownEnemy.spriteBody.position=ccp([self randomFloatBetween:startPosition.x - gameMapData.wayWidth/2 and:startPosition.x + gameMapData.wayWidth/2], startPosition.y);
    unknownEnemy.spriteBody.anchorPoint=ccp(0.5,0);
    if([_enemyInfo.enemyType isEqualToString:@"Demon Lord"]){
        unknownEnemy.spriteBody.position=startPosition;
    }
    
    [mapBackgroundSprite addChild:unknownEnemy.spriteBody z:2];
    [self addGameObject:unknownEnemy];
}

//when enemy arrive to the destination
-(void)enemyRunOverDestination:(GameObject *)_enemy {
    [_enemy.spriteBody removeFromParentAndCleanup:YES];
    [self removeGameObject:_enemy];
    mainGUIController.playerData.life--;
    [self drawPlayerInfo];
}

//fire at enemy
-(void)fireEnemy:(CGPoint)_targetPoint tower:(GameObject *)tower bullet:(GameObject *)_bullet {
    [mapBackgroundSprite addChild:_bullet.spriteBody z:2];
    [self addGameObject:_bullet];
    [(BulletObject *)_bullet fireTarget:_targetPoint];
}


//gesture event

//single tap
-(void)singleTapEvent:(UITapGestureRecognizer *)_singleTap {
    CGPoint touchLocation = [_singleTap locationInView:_singleTap.view];
    touchLocation = [[CCDirector sharedDirector] convertToGL:touchLocation];
    touchLocation = [self convertToNodeSpace:touchLocation];
    touchLocation=ccp(touchLocation.x-mapBackgroundSprite.position.x, touchLocation.y-mapBackgroundSprite.position.y);
    //    NSLog(@"Touch Location x=%f, y=%f",touchLocation.x,touchLocation.y);
    //    NSLog(@"Barrack Location x=%f, y=%f",temp.spriteBody.position.x*scaleRate-mapBackgroundSprite.position.x,temp.spriteBody.position.y*scaleRate-mapBackgroundSprite.position.y);
    //    NSLog(@"Scale Rate %f",scaleRate);
    CGPoint barrackPosition=ccpMult(temp.spriteBody.position,scaleRate);
    if (ccpDistance(barrackPosition, touchLocation)<temp.maxRadiusFireTarget*scaleRate){
        [temp newRallyPoint:ccpMult(touchLocation, 1/scaleRate)];
        NSLog(@"New Rally Point x=%f y=%f",temp.rallyPoint.position.x,temp.rallyPoint.position.y);
        setRallyPointMode=NO;
    }
    
}

//double tap
-(void)doubleTapEvent:(UITapGestureRecognizer*)_doubleTap {
    if(!setRallyPointMode){
        CGPoint touchLocation = [_doubleTap locationInView:_doubleTap.view];
        touchLocation = [[CCDirector sharedDirector] convertToGL:touchLocation];
        touchLocation = [self convertToNodeSpace:touchLocation];
        //NSLog(@"touch location x=%f, y=%f",touchLocation.x,touchLocation.y);
        CGSize s = [[CCDirector sharedDirector] winSize];
        //NSLog(@"winsize width=%f, height=%f",s.width,s.height);
        if (!zoomIn){
            scaleRate=s.width/mapBackgroundSprite.contentSize.width;
            [mapBackgroundSprite runAction:[CCScaleBy actionWithDuration:0.9f scaleX:scaleRate scaleY:scaleRate]];
            [mapBackgroundSprite runAction:[CCMoveTo actionWithDuration:1 position:ccp(0,0)]];
            zoomIn=YES;
        }
        else{
            scaleRate=1;
            CGRect firstQuarterScreen=CGRectMake(0,0, s.width/2, s.height/2);
            CGRect secondQuarterScreen=CGRectMake(s.width/2, 0, s.width/2, s.height/2);
            CGRect thirdQuarterScreen=CGRectMake(0, s.height/2, s.width/2, s.height/2);
            CGRect fourthQuarterScreen=CGRectMake(s.width/2,s.height/2, s.width/2,s.height/2);
            
            CGPoint newPos=ccp(0,0);
            if([self pointIsInRect:touchLocation withRect:firstQuarterScreen]){
                newPos=ccp(0,0);
                //   NSLog(@"First Quarter");
            }
            else if([self pointIsInRect:touchLocation withRect:secondQuarterScreen]){
                newPos=ccp(-mapBackgroundSprite.contentSize.width+s.width,0);
                // NSLog(@"Second Quarter");
            }
            else if([self pointIsInRect:touchLocation withRect:thirdQuarterScreen]){
                newPos=ccp(0,-mapBackgroundSprite.contentSize.height+s.height);
                //  NSLog(@"Third Quarter");
            }
            else if([self pointIsInRect:touchLocation withRect:fourthQuarterScreen]){
                newPos=ccp(-mapBackgroundSprite.contentSize.width+s.width,-mapBackgroundSprite.contentSize.height+s.height);
                //  NSLog(@"Fourth Quarter");
            }
            [mapBackgroundSprite runAction:[CCScaleTo actionWithDuration:0.9f scaleX:scaleRate scaleY:scaleRate]];
            [mapBackgroundSprite runAction:[CCMoveTo actionWithDuration:1 position:newPos]];
            zoomIn=NO;
        }
        
    }
}


//drag
- (void)handlePanFrom:(UIPanGestureRecognizer *)recognizer {    
    //NSLog(@"Gesture Clicked");
    if (recognizer.state == UIGestureRecognizerStateBegan) {    
        
        CGPoint touchLocation = [recognizer locationInView:recognizer.view];
        touchLocation = [mainGUIController.mainDirector convertToGL:touchLocation];
        touchLocation = [self convertToNodeSpace:touchLocation];                
        
    } else if (recognizer.state == UIGestureRecognizerStateChanged) {    
        
        CGPoint translation = [recognizer translationInView:recognizer.view];
        translation = ccp(translation.x, -translation.y);
        CGPoint newPos = ccpAdd(mapBackgroundSprite.position, translation);
        mapBackgroundSprite.position = [self boundLayerPos:newPos];  
        [recognizer setTranslation:CGPointZero inView:recognizer.view];    
        
    } else if (recognizer.state == UIGestureRecognizerStateEnded) {
        
        float scrollDuration = 0.2;
        CGPoint velocity = [recognizer velocityInView:recognizer.view];
        CGPoint newPos = ccpAdd(mapBackgroundSprite.position, ccpMult(ccp(velocity.x, velocity.y * -1), scrollDuration));
        newPos = [self boundLayerPos:newPos];
        [mapBackgroundSprite stopAllActions];
        CCMoveTo *moveTo = [CCMoveTo actionWithDuration:scrollDuration position:newPos];            
        [mapBackgroundSprite runAction:[CCEaseOut actionWithAction:moveTo rate:1]];            
        
    }        
}

//function use to calculate
- (CGPoint)boundLayerPos:(CGPoint)newPos {
    CGSize winSize = mainGUIController.mainDirector.winSize;
    CGPoint retval = newPos;
    scaleRate=1;
    if (zoomIn)
        scaleRate=winSize.width/mapBackgroundSprite.contentSize.width;
    retval.x = MIN(retval.x, 0);
    retval.x = MAX(retval.x, -mapBackgroundSprite.contentSize.width*scaleRate+winSize.width); 
    retval.y = MIN(0, retval.y);
    retval.y = MAX(-mapBackgroundSprite.contentSize.height*scaleRate+winSize.height, retval.y);
    //NSLog(@"bound x=%f,y=%f",retval.x,retval.y);
    return retval;
}

- (float)randomFloatBetween:(float)smallNumber and:(float)bigNumber {
    float diff = bigNumber - smallNumber;
    return (((float) (arc4random() % ((unsigned)RAND_MAX + 1)) / RAND_MAX) * diff) + smallNumber;
}

-(BOOL)pointIsInRect:(CGPoint)point withRect:(CGRect)rect{
	bool isInRect = false;
	if( point.x < rect.origin.x + rect.size.width && 
	   point.x > rect.origin.x &&
	   point.y < rect.origin.y + rect.size.height &&
	   point.y > rect.origin.y ){
		isInRect = true;
	}
	return isInRect;
}

-(void)callFireDropAttack:(id)sender {
    fireSkillCountDown = FIRE_SKILL_COUNT_DOWN;
    blackSpriteOfFireSkill.scaleY = 1.0f;
    fireSkillButton.isTouchEnabled = NO;
    fireEffect.visible = NO;
    
    [mainGUIController playEffect:AUDIO_EXPLOSIVE];
    
    CGSize size = mapBackgroundSprite.contentSize;
    
    for(int i = 0; i<self.listGameObject.count; i++) {
        if([[self.listGameObject objectAtIndex:i]isKindOfClass:[Enemy class]]) {
            FireDropObject *fireDrop = [[FireDropObject alloc] initFireDropObjectWith:self];
            [fireDrop.spriteBody setPosition:ccp(size.width/2, size.height)];
            [mapBackgroundSprite addChild:fireDrop.spriteBody z:5];
            [self addGameObject:fireDrop];
            [fireDrop dropToTarget:[self.listGameObject objectAtIndex:i]];
        }
    }
}

-(void)callSilverLightAttack:(id)sender {  
    lightkillCountDown = LIGHT_SKILL_COUNT_DOWN;
    blackSpriteOfLightSkill.scaleY = 1.0f;
    silverLightSkillButton.isTouchEnabled = NO;
    lightningEffect.visible = NO;
    
    [mainGUIController playEffect:AUDIO_SILVER_LIGHT];
    
    CGSize size = mapBackgroundSprite.contentSize;
    
    for(int i = 0; i<self.listGameObject.count; i++) {
        if([[self.listGameObject objectAtIndex:i]isKindOfClass:[Enemy class]]) {
            SilverLightObject *lightDrop = [[SilverLightObject alloc] initSilverLightObjectWith:self];
            [lightDrop.spriteBody setPosition:ccp(size.width/2, size.height)];
            [mapBackgroundSprite addChild:lightDrop.spriteBody z:5];
            [self addGameObject:lightDrop];
            [lightDrop dropToTarget:[self.listGameObject objectAtIndex:i]];
        }
    }
}

-(void)callHero:(id)sender{
    CGPoint secondLastPoint=[[[gameMapData.ways objectAtIndex:0] objectAtIndex:1] CGPointValue];
    int direction= [self directionFromPoint:callHeroMenu.position toDestinationPoint:secondLastPoint];
    float degree=0;
    if (direction==DIRECTION_UP){
        degree=-45;
    }
    else if (direction==DIRECTION_LEFT){
        degree=215;
    }
    else if (direction==DIRECTION_DOWN){
        degree=125;
    }
    else if (direction==DIRECTION_RIGHT){
        degree=45;
    }
    
    for (int i=0;i<3;i++){
        Hero *hero=[[Hero alloc]initHeroWithGameLayer:self];
        float radian=[hero degreesToRadians:(degree-i*45)];
        hero.standingPosition=ccp(callHeroMenu.position.x-30*cos(radian),callHeroMenu.position.y-30*sin(radian));
        [hero summonHero];
    }
    
    [callHeroMenu runAction:[CCScaleTo actionWithDuration:1.0 scale:0]];
    [callHeroMenu removeFromParentAndCleanup:YES];
}

-(void)pressStartWave:(id)sender{
    [self schedule:@selector(startWave:)];
    [startWaveMenu runAction:[CCScaleTo actionWithDuration:1.0 scale:0]];
    [startWaveMenu removeFromParentAndCleanup:YES];
}

//fixed
-(int)directionFromPoint:(CGPoint)_pointStart toDestinationPoint:(CGPoint)_pointEnd {
    
    CGPoint vector=ccp(_pointEnd.x-_pointStart.x ,_pointEnd.y-_pointStart.y);
    
    if(vector.y == 0){ 
        vector.y = 0.000001f; 
    }
    GameObject *gameobject=[[GameObject alloc]initGameObjectWith:self];
    float radians = atan(vector.x/vector.y);
    if(vector.y < 0){ 
        radians += 3.14159;
    }
    
    
    float degrees = [gameobject radiansToDegrees:radians];
    
    int direction=NO_DIRECTION;
    if(degrees >= 45.0 && degrees < 125.0){
        direction = DIRECTION_LEFT;
    }else if(degrees >= -45.0 && degrees < 45.0){
        direction = DIRECTION_UP;
    }else if(degrees >= 125.0 && degrees <215.0){
        direction = DIRECTION_DOWN;
    }else{
        direction = DIRECTION_RIGHT;
    }
    return direction;
}
//end fixed

-(void)dealloc {   
    NSLog(@"Play screen dealloc");
    [[mainGUIController.mainDirector openGLView] removeGestureRecognizer:singleTap];
    [[mainGUIController.mainDirector openGLView] removeGestureRecognizer:doubleTap];
    [[mainGUIController.mainDirector openGLView] removeGestureRecognizer:recognizerTap];
    
    [blackSpriteOfFireSkill stopAllActions];
    [blackSpriteOfFireSkill removeAllChildrenWithCleanup:YES];
    [blackSpriteOfFireSkill removeFromParentAndCleanup:YES];
    [blackSpriteOfFireSkill release];
    
    [blackSpriteOfLightSkill stopAllActions];
    [blackSpriteOfLightSkill removeAllChildrenWithCleanup:YES];
    [blackSpriteOfLightSkill removeFromParentAndCleanup:YES];
    [blackSpriteOfLightSkill release];
    
    [lightningEffect stopAllActions];
    [lightningEffect removeAllChildrenWithCleanup:YES];
    [lightningEffect removeFromParentAndCleanup:YES];
    [lightningEffect release];
    
    [fireEffect stopAllActions];
    [fireEffect removeAllChildrenWithCleanup:YES];
    [fireEffect removeFromParentAndCleanup:YES];
    [fireEffect release];
    
    [mapBackgroundSprite stopAllActions];
    [mapBackgroundSprite removeAllChildrenWithCleanup:YES];
    [mapBackgroundSprite removeFromParentAndCleanup:YES];
    [mapBackgroundSprite release];
    
    [self stopAllActions];
    [self removeAllChildrenWithCleanup:YES];
    [self removeFromParentAndCleanup:YES];
    
    [mainGUIController cleanupFrameCacheSprite];
    
    [super dealloc];
}

@end
